'use strict'
const svgCaptcha = require('svg-captcha')
const BaseController = require('./base')
const path = require('path')
const fse = require('fs-extra')
class UtilController extends BaseController {
  async captcha() {
    const captcha = svgCaptcha.create({
      size: 4,
      fontSize: 50,
      width: 100,
      height: 40,
      noise: 3,
    })
    this.ctx.session.captcha = captcha.text
    this.ctx.response.type = 'image/svg+xml'
    this.ctx.body = captcha.data
  }
  async sendcode() {
    const { ctx } = this
    const email = ctx.query.email
    const code = Math.random().toString().slice(2, 8)
    console.log('邮箱' + email + '验证码：' + code)
    ctx.session.emailcode = code
    const subject = 'web前端工作室验证码'
    const text = ''
    const html = `<h2>web前端社区</h2><a href="htt://www.kaikkeba.com"><span>${code}</span></a>`
    const hasSend = await this.service.tools.sendMail(email, subject, text, html)
    if (hasSend) {
      this.message('发送成功')
    } else {
      this.error('发送失败')
    }
  }
  //  判断文件是否上传过，如果没有是否有上传的切片
  async checkfile() {
    const { ctx } = this
    const { ext, hash } = ctx.request.body
    const filePath = path.resolve(this.config.UPLOAD_DIR, `${hash}.${ext}`)
    let uploaded = false
    let uploadedList = []
    if (fse.existsSync(filePath)) {
      uploaded = true
    } else {
      uploadedList = await this.getUploadList(path.resolve(this.config.UPLOAD_DIR, hash))
    }
    this.success({
      uploaded,
      uploadedList,
    })
  }
  // 获取文件切片 .DS_Store
  async getUploadList(dirPath) {
    return fse.existsSync(dirPath) ? (await fse.readdir(dirPath)).filter(name => name[0] !== '.') : []
  }
  async mergefile() {
    const { ext, size, hash, totalSize } = this.ctx.request.body
    const filePath = path.resolve(this.config.UPLOAD_DIR, `${hash}.${ext}`) // 文件存储的的位置，合并之后
    await this.ctx.service.tools.mergeFile(filePath, hash, size, totalSize)
    this.success({
      url: `/public/${hash}.${ext}`,
    })
  }
  async uploadfile() {
    // pulic/hash/(hash+index) // 切边存储格式
    // 报错状态模拟
    // if (Math.random() > 0.7) {
    //   return this.ctx.status = 500
    // }
    const { ctx } = this
    const file = ctx.request.files[0]
    const { hash, name } = ctx.request.body

    const chunkPath = path.resolve(this.config.UPLOAD_DIR, hash) // 切片存储的路径
    // const filePath = path.resolve(this.config.UPLOAD_DIR, hash) // 文件存储的的位置，合并之后 文件秒传

    if (!fse.existsSync(chunkPath)) {
      await fse.mkdir(chunkPath)
    }

    await fse.move(file.filepath, `${chunkPath}/${name}`) // 文件从临时目录运动到正式目录
    this.message('切边上传成功')

    // await fse.move(file.filepath, this.config.UPLOAD_DIR + '/' + file.filename) // 普通文件整体上传
    // this.success({
    //   url: `/public/${file.filename}`,
    // })
  }
}

module.exports = UtilController
